package com.me.study.socket.io;

import org.apache.commons.lang3.RandomStringUtils;

import java.io.*;
import java.net.Socket;
import java.text.MessageFormat;

/**
 * Socket编程：客户端
 *
 * @author ME
 * @date 2019/4/26
 */
public class SocketClient {

    private static MessageFormat format = new MessageFormat("Hello Server, I''m {0}.");

    public static void main(String args[]) throws Exception {
        // 服务端IP
        String host = "127.0.0.1";
        // 服务端端口
        int port = 8899;
        // 与服务端建立连接
        Socket client = new Socket(host, port);

        // 建立连接后就可以往服务端写数据了
        PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
        String msg = format.format(new Object[]{ RandomStringUtils.random(3, true, false)});
        System.out.println("【client】 " + msg);
        writer.println(msg);
        writer.println(SocketServer.END);
        // TODO client 主动关闭，服务端会收到正常关闭的终止符
        // client.shutdownOutput();

        // 写完以后进行读操作
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        StringBuilder resp = new StringBuilder();
        String inputLine;
        int index;
        while ((inputLine = reader.readLine()) != null) {
            if ((index = inputLine.indexOf(SocketServer.EOF)) != -1) {
                resp.append(inputLine, 0, index);
                break;
            }
            resp.append(inputLine);
        }
        System.out.println("\n【server】 " + resp);

        // TODO 应该调用 socket.close 自动关闭 IO流，避免不可预期的错误
        // writer.close();reader.close();
        client.close();
    }
}
